#include "DataCollector.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

DataCollector::DataCollector(QObject *parent)
    : QObject(parent),
      m_modbusService(nullptr),
      m_collectionTimer(new QTimer(this)),
      m_collectionInterval(1000),
      m_isCollecting(false),
      m_totalCollections(0),
      m_successfulCollections(0),
      m_failedCollections(0),
      m_waitingForReply(false)
{
    m_collectionTimer->setSingleShot(false);
    m_collectionTimer->setInterval(m_collectionInterval);
    connect(m_collectionTimer, &QTimer::timeout,
            this, &DataCollector::onCollectData);
}

DataCollector::~DataCollector()
{
    stopCollection();
}

void DataCollector::setDevice(const Device &device)
{
    m_device = device;
    qInfo() << "DataCollector: 设置采集设备" << device.deviceId();
}

void DataCollector::setModbusService(ModbusService *service)
{
    if (m_modbusService == service)
        return;

    if (m_modbusService)
    {
        disconnect(m_modbusService, nullptr, this, nullptr);
    }

    m_modbusService = service;

    if (m_modbusService)
    {
        connect(m_modbusService, &ModbusService::registersRead,
                this, &DataCollector::onRegistersRead, Qt::QueuedConnection);
        connect(m_modbusService, &ModbusService::readError,
                this, &DataCollector::onReadError, Qt::QueuedConnection);
    }
}

void DataCollector::setCollectionInterval(int intervalMs)
{
    m_collectionInterval = intervalMs;

    if (m_collectionTimer)
    {
        m_collectionTimer->setInterval(intervalMs);
    }
}

void DataCollector::startCollection()
{
    if (m_isCollecting)
    {
        qWarning() << "DataCollector: 采集已在运行";
        return;
    }

    if (m_device.deviceId().isEmpty())
    {
        qWarning() << "DataCollector: 未设置采集设备";
        return;
    }

    if (!m_modbusService)
    {
        qWarning() << "DataCollector: 未绑定 ModbusService";
        emit collectionFailed(m_device.deviceId(), "Modbus 服务未就绪");
        return;
    }

    if (!m_modbusService->isConnected())
    {
        qWarning() << "DataCollector: 设备未连接";
        emit collectionFailed(m_device.deviceId(), "设备未连接");
        return;
    }

    m_waitingForReply = false;
    m_isCollecting = true;
    m_totalCollections = 0;
    m_successfulCollections = 0;
    m_failedCollections = 0;

    m_collectionTimer->start();
    emit collectionStateChanged(true);

    qInfo() << "DataCollector: 启动数据采集 -" << m_device.deviceId()
            << "周期:" << m_collectionInterval << "ms";

    // 立即进行一次采集，减少首次延迟
    onCollectData();
}

void DataCollector::stopCollection()
{
    if (!m_isCollecting)
        return;

    m_collectionTimer->stop();
    m_isCollecting = false;
    m_waitingForReply = false;

    emit collectionStateChanged(false);
    qInfo() << "DataCollector: 停止数据采集 -" << m_device.deviceId();
}

void DataCollector::onCollectData()
{
    if (!m_modbusService || !m_modbusService->isConnected())
    {
        qWarning() << "DataCollector: 设备未连接，无法采集";
        emit collectionFailed(m_device.deviceId(), "设备未连接");
        return;
    }

    if (m_waitingForReply)
    {
        qWarning() << "DataCollector: 上次采集未完成，跳过本次";
        return;
    }

    m_waitingForReply = true;
    m_totalCollections++;

    if (!m_modbusService->readInputRegisters(0, 6))
    {
        m_waitingForReply = false;
        m_failedCollections++;
        qWarning() << "DataCollector: 发送读取请求失败";
        emit collectionFailed(m_device.deviceId(), "发送读取请求失败");
    }
}

void DataCollector::onRegistersRead(int startAddress, const QVector<quint16> &values)
{
    if (!m_isCollecting)
        return;

    m_waitingForReply = false;

    if (startAddress != 0 || values.size() < 6)
    {
        m_failedCollections++;
        qWarning() << "DataCollector: 寄存器数据不完整";
        emit collectionFailed(m_device.deviceId(), "寄存器数据不完整");
        return;
    }

    const float temperature = ModbusHelper::parseTemperature(values, 0);
    const float pressure = ModbusHelper::parsePressure(values, 2);
    const float flow = ModbusHelper::parseFlow(values, 4);

    DataPoint dataPoint(m_device.deviceId(), temperature, pressure, flow);

    if (saveToDatabase(dataPoint))
    {
        m_successfulCollections++;
        emit dataCollected(dataPoint);
        emit collectionSuccess(m_device.deviceId());

        qDebug() << "DataCollector: 采集成功 -"
                 << "温度:" << QString::number(temperature, 'f', 1) << "℃"
                 << "压力:" << QString::number(pressure, 'f', 1) << "kPa"
                 << "流量:" << QString::number(flow, 'f', 2) << "L/min";
    }
    else
    {
        m_failedCollections++;
        emit collectionFailed(m_device.deviceId(), "数据库保存失败");
    }
}

void DataCollector::onReadError(const QString &error)
{
    if (!m_isCollecting)
        return;

    m_waitingForReply = false;
    m_failedCollections++;

    qWarning() << "DataCollector: 读取失败 -" << error;
    emit collectionFailed(m_device.deviceId(), error);
}

bool DataCollector::saveToDatabase(const DataPoint &dataPoint)
{
    QSqlDatabase db = DatabaseService::instance()->database();
    if (!db.isValid())
    {
        qWarning() << "DataCollector: 数据库连接无效";
        return false;
    }

    QSqlQuery query(db);
    query.prepare(R"(
        INSERT INTO realtime_data (device_id, timestamp, temperature, pressure, flow)
        VALUES (?, datetime('now', 'localtime'), ?, ?, ?)
    )");

    query.addBindValue(dataPoint.deviceId());
    query.addBindValue(dataPoint.temperature());
    query.addBindValue(dataPoint.pressure());
    query.addBindValue(dataPoint.flow());

    if (!query.exec())
    {
        qWarning() << "DataCollector: 数据库保存失败:" << query.lastError().text();
        return false;
    }

    return true;
}
